import java.net.*;
import java.io.*;

public class Client
{
	public static void main(String args[])
	{
		Socket clientSocket = null;
		if (args.length < 2){
			System.out.println("Wywoanie programu: Client host port");
			System.exit(-1);
		}
		String host = args[0];
		int port = 0;
		try{
			port = new Integer(args[1]).intValue();
		}
		catch(NumberFormatException e){
			System.out.println("Nieprawidowy argument: port");
			System.exit(-1);
		}
		try{
			clientSocket = new Socket(host, port);
		}
		catch(UnknownHostException e){
			System.out.println("Nieznany host.");
			System.exit(-1);
		}
		catch(ConnectException e){
			System.out.println("Poczenie odrzucone.");
			System.exit(-1);
		}
		catch(IOException e){
			System.out.println("Bd wejcia-wyjcia: " + e);
			System.exit(-1);
		}
		System.out.println("Poczono z " + clientSocket);

		String line = null;
		BufferedReader brSocket = null;
		BufferedReader brInput = null;
		DataOutputStream out = null;
		
		try{
			out = new DataOutputStream(clientSocket.getOutputStream());
		brSocket = new BufferedReader (new InputStreamReader (clientSocket.getInputStream()));
			brInput = new BufferedReader(new InputStreamReader(System.in));
		}
		catch(IOException e){
			System.out.println("Bd przy tworzeniu strumieni: " + e);
			System.exit(-1);
		}
		while(true){
			try{
				line = brInput.readLine();
				System.out.println("Wsysyam: " + line);
				out.writeBytes(line + '\n');
				out.flush();
				if (line.equals("quit")){
					System.out.println("Koczenie pracy...");
					clientSocket.close();
					System.exit(0);
				}
				brSocket.readLine();
				System.out.println("Otrzymano: " + line);
			}
			catch(IOException e){
				System.out.println("Bd wejcia-wyjcia: " + e);
				System.exit(-1);
			}
			catch(Exception e){
				System.out.println("Bd oglny: " + e);
			}
		}
	}
}
